package com.weiqiao.api.service.impl;

import com.google.gson.Gson;
import com.mingsoft.util.StringUtil;
import com.weiqiao.api.domain.CommodityApiEntity;
import com.weiqiao.api.domain.vo.CommodityApiVO;
import com.weiqiao.api.repository.ICommodityApiRepository;
import com.weiqiao.api.service.ICommodityApiService;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author PEI
 * @Description
 * @Date 2020/7/27 17:08
 */
@Service("CommodityApiService")
public class CommodityApiService implements ICommodityApiService {

    @Autowired
    private ICommodityApiRepository commodityApiRepository;

    @Override
    public List<CommodityApiEntity> findCommodity(CommodityApiVO vo) {
        // 查询条件拼接
        Document doc = getParam(vo);
        // 分页条件拼接
        int skip = vo.getPage() * vo.getSize();
        Bson sort = new Document("create_date", -1);

        int company_id = vo.getCompany_id();
        List<CommodityApiEntity> commodityList = new ArrayList<>();
        List<String> list = commodityApiRepository.getPageList(company_id, doc, sort, skip, vo.getSize());
        if (!list.isEmpty()) {
            for (String a : list) {
                CommodityApiEntity c = new Gson().fromJson(a, CommodityApiEntity.class);
                commodityList.add(c);
            }
        }
        return commodityList;
    }

    @Override
    public CommodityApiEntity findCommodityDetail(CommodityApiVO vo) {
        Integer company_id = vo.getCompany_id();
        String commodity_s = commodityApiRepository.findCommodityDetail(
                new Document()
                        .append("commodity_id", vo.getCommodity_id())
                        .append("company_id", company_id)
                        .append("state", 0)
                        .append("delete_flag", 0)
        );
        return StringUtil.isBlank(commodity_s) ? new CommodityApiEntity() : new Gson().fromJson(commodity_s, CommodityApiEntity.class);
    }

    /**
     * 拼接检索条件
     *
     * @param vo
     * @return
     */
    private Document getParam(CommodityApiVO vo) {
        Document doc = new Document("delete_flag", 0);

        // 根据标签进行查询
        if (!StringUtil.isBlank(vo.getLabel_brand_id())) {
            doc.append("label_brand_ids", vo.getLabel_brand_id());
        }

        // 根据商品id进行查询
        if (!StringUtil.isBlank(vo.getCommodity_id())) {
            doc.append("commodity_id", vo.getCommodity_id());
        }

        // 是否是积分商品进行查询 不填查所有，0只查询普通商品 1，只查询积分商品
        if (StringUtil.isInteger(vo.getIs_score_commodity())) {
            doc.append("is_score_commodity", vo.getIs_score_commodity());
        }
        return doc;
    }
}
